package com.ys.bean.factory;

import com.ys.bean.support.BeanDefinition;
import com.ys.bean.support.BeanReference;
import com.ys.bean.support.PropertyValue;

import java.lang.reflect.Field;

/**
 * <p>@description:可自动装配内容的BeanFactory</p>
 *
 * @projectName: Spring-Mini
 * @packageName: com.com.ys.bean.factory
 * @className:
 * @author: shuangyang
 * @date: 1/14/17 9:43 PM
 */
public class AutowireCapableBeanFactory extends AbstractBeanFactory {

    @Override
    protected Object generateBean(BeanDefinition definition) throws Exception {
        Class<?> clazz = definition.getBeanClass();
        Object beanInstance;
        //生成bean实例
        beanInstance = clazz.newInstance();
        //生成bean属性
        applyPropertyValues(beanInstance, definition);
        return beanInstance;
    }

    private void applyPropertyValues(Object beanInstance, BeanDefinition definition) throws Exception {

        for (PropertyValue propertyValue : definition.getPropertyValues().getPropertyValueList()) {
            //根据属性好哦取方法名
            Field declaredField = beanInstance.getClass().getDeclaredField(propertyValue.getName());
            //设在私有字段可访问
            declaredField.setAccessible(true);
            //判断并注入属性
            Object value = propertyValue.getValue();
            //判断是否是引用类型
            if (value instanceof BeanReference) {
                BeanReference beanReference = (BeanReference) value;
                value = getBeanByName(beanReference.getName());
            }
            //字段赋值
            declaredField.set(beanInstance, value);
        }

    }


}
